package com.maila.company.iterget;


import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import java.util.List;

public class MainActivity extends AppCompatActivity {

    WebView mWebView;
    ProgressBar progressBar;
    ActionBar toolbar;
    TextView textView;
    View mErrorView;
    boolean mIsErrorPage;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        init();
        setupWebView();
        mWebView.loadUrl("http://m.maila88.com/mailaIndex?mailaAppKey=VPe3d6hZLhQdRo8jz2Fs6");
    }


    private void init() {
//        new UpdataManager(this).checkUpdate();
//        mErrorView = View.inflate(this, R.layout.activity_url_error, null);
        mErrorView = findViewById(R.id.online_error_btn_retry);
        mWebView = (WebView) findViewById(R.id.my_webview);
        progressBar = (ProgressBar) findViewById(R.id.mProgressBar);
        toolbar = getSupportActionBar();
        ColorDrawable colorDrawable = new ColorDrawable(Color.parseColor("#ffffffff"));
        toolbar.setBackgroundDrawable(colorDrawable);
        toolbar.setDisplayShowCustomEnabled(true);
        View actionBarView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.actionbar_layout, null);
        toolbar.setCustomView(actionBarView, new ActionBar.LayoutParams(ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT));
        textView = (TextView) findViewById(R.id.my_action_bar_title);
        toolbar.setDisplayShowTitleEnabled(false);
        toolbar.setDisplayHomeAsUpEnabled(false);

    }


    private void setupWebView() {
        final WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setDefaultTextEncodingName("UTF-8");
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setBuiltInZoomControls(false);
        webSettings.setUseWideViewPort(true);
        webSettings.setLoadWithOverviewMode(true);
        webSettings.setSupportZoom(false);
        webSettings.setDomStorageEnabled(true);
        webSettings.setLoadsImagesAutomatically(true);
        mWebView.setScrollContainer(false);
        mWebView.setVerticalScrollBarEnabled(false);
        mWebView.setHorizontalScrollBarEnabled(false);
        WebChromeClient webChromeClient = new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                super.onProgressChanged(view, newProgress);
                if (newProgress == 100) {
                    progressBar.setVisibility(View.INVISIBLE);
                } else {
                    progressBar.setVisibility(View.VISIBLE);
                    progressBar.setProgress(newProgress);
                }
            }
        };
        mWebView.setWebChromeClient(webChromeClient);

        WebViewClient webViewClient = new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                if (!Util.isNetworkConnected(MainActivity.this)) {
                    mIsErrorPage = true;
                    showNetErrorPage();
                } else {
                    mErrorView.setVisibility(View.GONE);
                }
            }

            @Override
            public void onLoadResource(WebView view, String url) {
                super.onLoadResource(view, url);

            }

            @Override
            public void onPageFinished(WebView view, String url) {

                if (view.getProgress() == 100) {
                    if (!mIsErrorPage) {
                        mErrorView.setVisibility(View.GONE);
                        mWebView.setVisibility(View.VISIBLE);
                    }
                }

                if (mWebView == null || mWebView.getTitle() == null || mWebView.getTitle().length() == 0) {
                    return;
                }
                if (textView == null) {
                    return;
                }

                if (mWebView.getTitle().length() >= 12) {
                    textView.setText(mWebView.getTitle().substring(0, 11) + "...");
                } else {
                    textView.setText(mWebView.getTitle());
                }
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Uri uri = Uri.parse("url");
                if (!url.startsWith("http://") && !url.startsWith("https://")) {
                    final PackageManager packageManager = MainActivity.this.getPackageManager();
                    final Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(uri);//Uri.parse("tbopen://m.taobao.com/tbopen/index.html?action=ali.open.nav&module=h5&appkey=23402401&backURL=&TTID=2014_0_23402401@baichuan_h5_0.0.3&bootImage=0&appName=&packageName=&source=bc&tag=&utdid=&scm=&pvid=&uri=https://taoquan.taobao.com/coupon/unify_apply.htm?sellerId=1114408582&activityId=c184815f21714efba5225887e75852cd&h5Url=https%3A%2F%2Ftaoquan.taobao.com%2Fcoupon%2Funify_apply.htm%3FsellerId%3D1114408582%26activityId%3Dc184815f21714efba5225887e75852cd%26params%3D%25257B%252522TTID%252522%25253A%2525222014_0_23402401%252540baichuan_h5_0.0.3%252522%25252C%252522source%252522%25253A%252522bc%252522%25252C%252522ybhpss%252522%25253A%252522dHRpZD0yMDE0XzBfMjM0MDI0MDElNDBiYWljaHVhbl9oNV8wLjAuMw%2525253D%2525253D%252522%25257D&params=%7B%22TTID%22%3A%222014_0_23402401%40baichuan_h5_0.0.3%22%2C%22source%22%3A%22bc%22%2C%22ybhpss%22%3A%22dHRpZD0yMDE0XzBfMjM0MDI0MDElNDBiYWljaHVhbl9oNV8wLjAuMw%253D%253D%22%7D"));
                    List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
                    if (list.size() > 0) {//可以处理此intent的情况
                        startActivity(intent);
                        return true;
                    }
                }
                return false;
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
                Uri uri = request.getUrl();
                String url = uri.toString();
                if (!url.startsWith("http://") && !url.startsWith("https://")) {
                    final PackageManager packageManager = MainActivity.this.getPackageManager();
                    final Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setData(uri);//Uri.parse("tbopen://m.taobao.com/tbopen/index.html?action=ali.open.nav&module=h5&appkey=23402401&backURL=&TTID=2014_0_23402401@baichuan_h5_0.0.3&bootImage=0&appName=&packageName=&source=bc&tag=&utdid=&scm=&pvid=&uri=https://taoquan.taobao.com/coupon/unify_apply.htm?sellerId=1114408582&activityId=c184815f21714efba5225887e75852cd&h5Url=https%3A%2F%2Ftaoquan.taobao.com%2Fcoupon%2Funify_apply.htm%3FsellerId%3D1114408582%26activityId%3Dc184815f21714efba5225887e75852cd%26params%3D%25257B%252522TTID%252522%25253A%2525222014_0_23402401%252540baichuan_h5_0.0.3%252522%25252C%252522source%252522%25253A%252522bc%252522%25252C%252522ybhpss%252522%25253A%252522dHRpZD0yMDE0XzBfMjM0MDI0MDElNDBiYWljaHVhbl9oNV8wLjAuMw%2525253D%2525253D%252522%25257D&params=%7B%22TTID%22%3A%222014_0_23402401%40baichuan_h5_0.0.3%22%2C%22source%22%3A%22bc%22%2C%22ybhpss%22%3A%22dHRpZD0yMDE0XzBfMjM0MDI0MDElNDBiYWljaHVhbl9oNV8wLjAuMw%253D%253D%22%7D"));
                    List<ResolveInfo> list = packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
                    if (list.size() > 0) {//可以处理此intent的情况
                        startActivity(intent);
                        return true;
                    }

                    return true;
                }

                return false;
            }

            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();  // 接受所有网站的证书
            }

            @RequiresApi(api = Build.VERSION_CODES.M)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                mIsErrorPage = true;
                Log.i("xianGetError", "error code=" + "  " + error.getErrorCode());
                showNetErrorPage();
                super.onReceivedError(view, request, error);
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                Log.i("xianGetError", "error code=" + "  " + errorCode);
                showNetErrorPage();
                mIsErrorPage = true;
            }
        };
        mWebView.setWebViewClient(webViewClient);

    }


    protected void showNetErrorPage() {

        if (mWebView != null) {
            mWebView.setVisibility(View.GONE);
        }
//        LinearLayout webParentView = (LinearLayout) findViewById(R.id.activity_my_webview);
//        while (webParentView.getChildCount() > 1) {
//            webParentView.removeViewAt(0);
//        }
//        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.FILL_PARENT);
//        webParentView.addView(mErrorView, 0, lp);
        initNetErrorPage();
    }

    protected void initNetErrorPage() {
        if (mErrorView != null) {
            mErrorView.setVisibility(View.VISIBLE);
            RelativeLayout button = (RelativeLayout) mErrorView.findViewById(R.id.online_error_btn_retry);
            button.setOnClickListener(new View.OnClickListener() {
                public void onClick(View v) {
                    mIsErrorPage = false;
                    mWebView.reload();
                }
            });
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mWebView.canGoBack()) {
            mWebView.goBack();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

}
